package net.obxlabs.tweetpad;

import java.util.*;
import net.obxlabs.tweetpad.stats.*;
import penner.easing.*;
import processing.core.*;

public class ThumbStrip extends Thread {
	public static final int ANIM_DURATION = 60;
	public static final int ANIM_SHIFT = -60;
	
	private PApplet p;
	private Mailman mailman;
	private Counter counter;
	private List<Tweet> tweets;
	private int fetchInterval;
	private boolean animating;
	private int animTime;
	
	public ThumbStrip(PApplet p, Mailman m, Counter c) {
		this(p, m, c, 1000*3);  // fetch every 3 seconds
	}
	
	public ThumbStrip(PApplet p, Mailman m, Counter c, int fetchInterval) {
		this.p = p;
		p.registerPre(this);
		
		mailman = m;
		counter = c;
		tweets = Collections.synchronizedList(new LinkedList<Tweet>());
		this.fetchInterval = fetchInterval;
		animating = false;
	}
	
	public void run() {
		while (true) {
            try {
                loadTweet();
                Thread.sleep(fetchInterval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
	}
	
	public void start(String name) {
        setName(name);
        setDaemon(true);
        start();
    }
	
	public synchronized void loadTweet() {
		if (mailman.hasMore()) {
			Tweet newTweet = mailman.getTweet();
			if (tweets.isEmpty()) {
				newTweet.setPosition(6, p.height-34);
			} else {
				newTweet.setPosition(6, tweets.get(tweets.size()-1).getY()+Tweet.THUMB_SIZE+12);
			}
			tweets.add(newTweet);
			counter.addCount(newTweet.getTextSource(), newTweet.getText());
			initAnim();
		}
	}
	
	public void initAnim() {
		animTime = 0;
		synchronized (tweets) {
			for (Tweet aTweet: tweets) {
				aTweet.initAnim();
			}
		}
		animating = true;
	}
	
	public void pre() {
		if (animating) {
			// calculate new positions for all Thumbnails
			synchronized (tweets) {
				for (Tweet aTweet : tweets) {
					aTweet.setY(Cubic.easeOut(animTime, aTweet.getSY(), ANIM_SHIFT, ANIM_DURATION));
				}
			}
			
			if (animTime < ANIM_DURATION) {
				animTime++;
			} else {
				animating = false;
			}
		}
		clean();
	}
	
	public synchronized void clean() {
		while (tweets.size() > 10) {
			Tweet topTweet = tweets.get(0);
			if (topTweet.getY() <= ANIM_SHIFT) {
				topTweet.destroy();
				tweets.remove(0);
			} else {
				break;
			}
		}
	}
	
	public synchronized void draw() {
		for (Tweet aTweet : tweets) {
			aTweet.drawThumbnail();
		}
	}
}
